package com.bondqin.sakila.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;

public class ConvertUtil {
	
	private ConvertUtil() {
	}
	
	public static <T> T copyConvert(Object source, Class<T> targetType) {
		Assert.notNull(source);
		Assert.notNull(targetType);
		
		T target = null;
		try {
			target = targetType.newInstance();
			BeanUtils.copyProperties(source, target);
		} catch (Exception e) {
		}
		return target;
	}

	public static <T> List<T> copyConvert(List<Object> sourceList, Class<T> targetType) {
		Assert.notNull(sourceList);
		Assert.notNull(targetType);
		
		List<T> targetList = new ArrayList<T>();
		
		for(Object source : sourceList) {
			T target = copyConvert(source, targetType);
			targetList.add(target);
		}
		return targetList;
	}
	
	public static <S, T> Page<T> copyConvert(Page<S> sourcePage, Class<T> targetType) {
		Assert.notNull(sourcePage);
		Assert.notNull(targetType);
		
		Page<T> targetPage = sourcePage.map(new Converter<S, T>() {
			@Override
			public T convert(S source) {
				T target = copyConvert(source, targetType);
				return target;
			}
		});
		return targetPage;
	}

}